<?php

namespace App\Http\Controllers\Apps;

use App\Http\Controllers\AppController;
use App\Http\Resources\Apps\CouponResource;
use App\Http\Resources\Apps\UserCouponRecordResource;
use App\Http\Resources\Apps\UserResource;
use App\Models\AppUserSign;
use App\Models\AppUserSmsCode;
use App\Models\Coupon;
use App\Models\Notice;
use App\Models\User;
use App\Models\UserCoupon;
use App\Models\UserCouponUseRecord;
use App\Models\UserSmsCode;
use App\Services\AliSms;
use App\Services\WechatApi;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class Member extends AppController
{

    public function sendCode(Request $request)
    {
        $validator = Validator::make($post = $request->all(),[
            'mobile'    => 'required|integer',
        ]);

        if ($validator->fails()){

            return $this->ReturnFailed(1);
        }

        $sms_code = UserSmsCode::where('mobile',$post['mobile'])->latest()->first();

        if ($sms_code && strtotime($sms_code->created_at) > time()+60){

            return $this->ReturnVerifyError(5); //发送频繁
        }

        $code = rand(1000,9999);

        $send = AliSms::sendCode($post['mobile'],1,['code'=>$code]);

        if ($send['Code'] != 'OK'){

            return $this->ReturnVerifyError(4,$send['Message']);//发送失败
        }

        UserSmsCode::create([
            'mobile'    => $post['mobile'],
            'code'      => $code
        ]);

        return $this->ReturnSuccessInfo();
    }

    public function wechatLogin(Request $request)
    {
        $validator = Validator::make($post = $request->all(),[
            'code'      => 'required',
        ]);

        if ($validator->fails()){

            return $this->ReturnFailed(1,$validator->errors());
        }

        if (! $data = WechatApi::getUser($post['code'])){

            return $this->ReturnVerifyError(103);
        }

        $user = User::where('openid',$data['openid'])->first();

        if (! $user){

            return $this->ReturnVerifyError(104,['openid'=>$data['openid']]);
        }

        $notice = Notice::latest()->first();

        return $this->ReturnSuccessInfo([
            'access_token'  => $this->auth()->attempt(['id'=>$user->id]),
            'token_type'    => 'bearer',
            'expires_in'    => $this->auth()->factory()->getTTL() * 60,
        ]);
    }

    public function wechatBind(Request $request)
    {
        $validator = Validator::make($post = $request->all(),[
            'mobile'    => 'required|integer',
            'code'      => 'required|integer',
            'openid'    => 'required',
            'rawData'   => 'required',
        ]);

        if ($validator->fails()){

            return $this->ReturnFailed(1,$validator->errors());
        }

        if ($verifyCode = $this->verifySmsCode($post['mobile'],$post['code'])){

            return $this->ReturnVerifyError($verifyCode);
        }

        $raw = json_decode($post['rawData']);

        $user = User::updateOrCreate(['mobile'=>$post['mobile']]);

        $flag = User::find($user->id);
        $flag->icon = $raw->avatarUrl;
        $flag->nickname = $raw->nickName;
        $flag->openid = $post['openid'];
        $flag->save();

        return $this->ReturnSuccessInfo();
    }

    public function personal()
    {
        return $this->ReturnSuccessInfo(UserResource::make(User::find($this->auth()->user()->id)));
    }

    public function personalUpdate(Request $request)
    {
        $validator = Validator::make($post = $request->all(),[
            'name'      => 'required',
            'identity'  => 'required',
            'address'   => 'required',
        ]);

        if ($validator->fails()){

            return $this->ReturnFailed(1,$validator->errors());
        }

        User::find($this->auth()->user()->id)->update($post);

        return $this->ReturnSuccessInfo();
    }

    public function coupon(Request $request)
    {
        $elem = UserCoupon::latest()
                            ->where('user_id',$this->auth()->user()->id);

        $data = $elem->paginate($request->input('num',10));

        return $this->ReturnPage(CouponResource::collection($data));
    }

    public function couponUseRecord(Request $request)
    {
        $elem = UserCouponUseRecord::latest()
                                    ->where('user_id',$this->auth()->user()->id);

        $data = $elem->paginate($request->input('num',10));

        return $this->ReturnPage(UserCouponRecordResource::collection($data));
    }

    public function sign_in()
    {
        AppUserSign::firstOrCreate(['date'=>date('Y-m-d')],[
            'user_id'   => $this->auth()->user()->id,
        ]);

        return $this->ReturnSuccessInfo();
    }

    public function couponUse(Request $request)
    {
        $validator = Validator::make($post = $request->all(),[
            'coupon_id' => 'required|integer|exists:user_coupons,id',
            'amount'    => 'required|numeric',
            'price'     => 'required|numeric',
            'desc'      => 'required'
        ]);

        if ($validator->fails()){

            return $this->ReturnFailed(1,$validator->errors());
        }

        if (!$this->auth()->user()->is_admin){

            return $this->ReturnVerifyError(105);
        }

        $coupon = UserCoupon::find($post['coupon_id']);

        if ($coupon->value < $post['price']){

            return $this->ReturnVerifyError(12);
        }

        UserCouponUseRecord::create([
            'user_id'   => $coupon->user_id,
            'coupon_id' => $post['coupon_id'],
            'amount'    => $post['amount'],
            'price'     => $post['price'],
            'admin_id'  => $this->auth()->user()->id,
            'desc'      => $post['desc'],
        ]);

        return $this->ReturnSuccessInfo();
    }

    public function qcode(Request $request)
    {
        $validator = Validator::make($post = $request->all(),[
            'page'  => 'required',
            'params'=> 'required|array',
            'width' => 'required|integer',
        ]);

        if ($validator->fails()){

            return $this->ReturnFailed(1,$validator->errors());
        }

        $url = WechatApi::createQRCode($post['page'],$post['params'],$post['width']);

        return $this->ReturnSuccessInfo([
            'url'   => $url,
        ]);
    }


    public function inviteQcode(Request $request)
    {
        $validator = Validator::make($post = $request->all(),[
            'invite'    => 'required|integer',
            'width'     => 'required|integer',
        ]);

        if ($validator->fails()){

            return $this->ReturnFailed(1,$validator->errors());
        }

        $url = WechatApi::createQRCode('pages/index/index',[
            'invite'    => $post['invite'],
        ],$post['width']);

        return $this->ReturnSuccessInfo([
            'url'   => $url,
        ]);
    }

    public function indexQcode(Request $request)
    {
        $url = WechatApi::createQRCode('pages/index/index',[
        ],$request->input('width',430));

        return $this->ReturnSuccessInfo([
            'url'   => $url,
        ]);
    }

}
